package com.platform.metamodel;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.metamodel.schema.ColumnType;
import org.apache.metamodel.schema.ColumnTypeImpl;
import org.apache.metamodel.schema.MutableColumn;

import java.util.Objects;

/**
 * @author Tommy
 * @create 2021/7/19 15:58
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class MtField {
    private String fieldName;
    private String fieldDesc;
    private int    fieldIndex;
    /**
     * 所属超类
     */
    private String superType;
    private String fieldType;
    private Integer size;
    // scale
    private Integer decimalDigits;
    private boolean primaryKey;

    public MtField(String fieldName, String fieldType, String superType, int fieldIndex){
        this.setFieldName(fieldName);
        this.setFieldType(fieldType);
        this.setSuperType(superType);
        this.setFieldIndex(fieldIndex);
    }

    public MtField(String fieldName, String fieldType, String superType, int fieldIndex, boolean primaryKey){
        this(fieldName, fieldType, superType, fieldIndex);
        this.setPrimaryKey(primaryKey);
    }

    public MtField(String fieldName, String fieldType, String superType, int fieldIndex, Integer size, boolean primaryKey){
        this(fieldName, fieldType, superType, fieldIndex);
        this.setSize(size);
        this.setPrimaryKey(primaryKey);
    }

    public MtField(String fieldName, String fieldType, String superType, int fieldIndex, Integer size, Integer decimalDigits){
        this(fieldName, fieldType, superType, fieldIndex);
        this.setSize(size);
        this.setDecimalDigits(decimalDigits);
    }

    public static MutableColumn of(MtField mtField){
        MutableColumn column = new MutableColumn(mtField.fieldName);
        if (Objects.nonNull(mtField.getFieldDesc())){
            column.setRemarks(mtField.getFieldDesc());
        }
        ColumnType columnType = new ColumnTypeImpl(mtField.getFieldType(),
                                            ColumnSupTypeUtil.getColumnSupType(mtField.getSuperType()));
        column.setType(columnType);
        column.setNativeType(columnType.getName());
        column.setColumnSize(mtField.getSize());
        column.setDecimalDigits(mtField.getDecimalDigits());
        if (mtField.isPrimaryKey()){
            column.setPrimaryKey(mtField.isPrimaryKey());
        }

        return column;
    }
}
